<?php
namespace app\api\service\ceping;

class ZikongliService {
    // 测评维度配置
	//每个维度需要几个问题，采用李克特量表，1到5分。positive正向negative反向
	//采用李克特5级量表（1=完全不符合，5=完全符合）：
    private $dimensions = [
        'impulse' => [
            'name' => '冲动控制',
            'questions' => [
                ['id' => 1, 'text' => '我常常不经思考就做出决定', 'type' => 'positive', 'weight' => 1.2],
                ['id' => 2, 'text' => '我能有效控制购物冲动', 'type' => 'negative', 'weight' => 1.1]
            ]
        ],
        'persistence' => [
            'name' => '目标坚持', 
            'questions' => [
                ['id' => 3, 'text' => '我能坚持完成长期计划', 'type' => 'negative', 'weight' => 1.3],
                ['id' => 4, 'text' => '经常半途而废放弃目标', 'type' => 'positive', 'weight' => 1.2]
            ]
        ],
        'delay' => [
            'name' => '延迟满足',
            'questions' => [
                ['id' => 5, 'text' => '我宁愿要立即的小奖励也不要未来的大回报', 'type' => 'positive', 'weight' => 1.1],
                ['id' => 6, 'text' => '能为长期目标放弃眼前诱惑', 'type' => 'negative', 'weight' => 1.4]
            ]
        ],
        'emotion' => [
            'name' => '情绪调节',
            'questions' => [
                ['id' => 7, 'text' => '情绪激动时仍能理性决策', 'type' => 'negative', 'weight' => 1.2],
                ['id' => 8, 'text' => '经常因情绪波动影响判断', 'type' => 'positive', 'weight' => 1.1]
            ]
        ]
    ];

    // 生成测评问卷
    public function generateTest() {
        $questionnaire = [];
        foreach ($this->dimensions as $dim) {
            shuffle($dim['questions']);
            $questionnaire = array_merge($questionnaire, $dim['questions']);
        }
        return $questionnaire;
    }

    // 计算测评结果
    public function calculateScore($answers) {
        $results = [];
        $total = 0;
        $maxPossible = 0;

        foreach ($this->dimensions as $key => $dim) {
            $dimScore = 0;
            foreach ($dim['questions'] as $q) {
                if (!isset($answers[$q['id']])) continue;

                // 处理反向计分
                $effectiveScore = ($q['type'] == 'negative') ? 
                                 (6 - $answers[$q['id']]) : 
                                 $answers[$q['id']];
                
                $dimScore += $effectiveScore * $q['weight'];
            }
            
            // 计算维度得分（0-100分）
            $maxDim = 5 * count($dim['questions']) * $q['weight'];
            $results[$key] = [
                'name' => $dim['name'],
                'score' => round(($dimScore / $maxDim) * 100, 1),
                'raw' => $dimScore
            ];
            
            $total += $dimScore;
            $maxPossible += $maxDim;
        }

        // 计算综合指数
        $totalScore = round(($total / $maxPossible) * 100, 1);
        
		//建议
		$suggestion = $this->generateAdvice(['score' => $totalScore,'level' => $this->getLevel($totalScore),'dimensions' => $results]);
		$results_new = [];
		foreach($results as $k=>$v){
			$results_new[$v['name']] = $v['score'];
		}
        return [
            'score' => $totalScore,
            'level' => $this->getLevel($totalScore),
            'suggestion' => $suggestion,
            'dimensions' => $results_new,
        ];
    }

    // 判断自控力等级
    private function getLevel($score) {
        if ($score >= 80) return '高自控力';
        if ($score >= 60) return '中等自控力';
        if ($score >= 40) return '自控力待提升';
        return '低自控力';
    }

    // 生成改进建议
    public function generateAdvice($results) {
        $advice = [];
        
        // 综合建议
        $advice[] = $this->getGeneralAdvice($results['level']);
        
        // 分维度建议
        foreach ($results['dimensions'] as $dim) {
            if ($dim['score'] < 60) {
                $advice[] = $this->getDimensionAdvice($dim['name'], $dim['score']);
            }
        }
        
        return array_unique($advice);
    }

    private function getGeneralAdvice($level) {
        $adviceMap = [
            '高自控力' => '保持现有习惯，注意避免过度自我压抑',
            '中等自控力' => '使用「如果-那么」计划法加强关键领域',
            '自控力待提升' => '建立微习惯系统，每天进行5分钟专注训练',
            '低自控力' => '建议从环境改造开始，移除明显诱惑源'
        ];
        return $adviceMap[$level];
    }

    private function getDimensionAdvice($dimName, $score) {
        $adviceMap = [
            '冲动控制' => '实施10分钟等待规则：做决定前等待10分钟',
            '目标坚持' => '使用SMART原则拆解目标，设置里程碑奖励',
            '延迟满足' => '建立愿望清单，设置达成条件才能获取奖励',
            '情绪调节' => '练习STOP技术：Stop→Take breath→Observe→Proceed'
        ];
        return $adviceMap[$dimName] ?? '加强'.$dimName.'专项训练';
    }
}

?>